package com.intretech.tj.web

import com.intretech.tj.light.Light
import com.intretech.tj.light.State
import com.intretech.tj.web.callback.FailBody
import com.intretech.tj.web.callback.SuccessBody
import com.intretech.tj.light.service.YamlService
import com.intretech.tj.web.callback.LightDataBody
import jakarta.enterprise.context.ApplicationScoped
import jakarta.ws.rs.*
import jakarta.ws.rs.core.MediaType
import lombok.extern.slf4j.Slf4j


@Path("/setting/light")
@ApplicationScoped
@Slf4j
class SettingLightResource() {

    private val yamlService: YamlService= YamlService();
    private var lightArray = yamlService.loadFromYaml("light.yaml", Array<Light>::class.java)



    @POST
    @Path("/save")
    @Produces(MediaType.APPLICATION_JSON)
    @Consumes(MediaType.APPLICATION_JSON)
    fun save(light: LightDataBody): Any {
        try {
            lightArray!!.forEach { if (it.id == light.id) {
                it.redTime = light.redTime;
                it.greenTime = light.greenTime;
                it.yellowTime = light.yellowTime;
                it.state = State.getState(light.state);
                it.time = light.time;
                }
            }
            yamlService.saveAsYaml(lightArray!!, "light.yaml");

            return SuccessBody(200, "success");

        }
        catch (e: Exception){
            return FailBody(500, e.message!!);
        }

    }
    @Path("/get")
    @GET
    @Produces(MediaType.APPLICATION_JSON)
    fun get(): Any {
        return try {
            SuccessBody(200, "success", lightArray);
        }catch (e: Exception){
            FailBody(500, e.message!!);
        }
    }
}